﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Web;
using System.Web.Script.Serialization;
using TTJ.DataModel;
using TTJ.DataModel.DataStruct.Pixabay;

namespace TTJ.Service.Pixabay
{
    public partial class PixabayHelper
    {
        private PixabayQueryData Query(string keyword)
        {
            PixabayQueryData result = null;
            if (string.IsNullOrEmpty(keyword)) return result;

            string url = UrlBase + "/api/?key=" + AppId + "&q=" + keyword + "&image_type=photo&pretty=true&per_page=" + CountPerPage;
            try
            {
                HttpWebRequest getAccessRequest = WebRequest.Create(url) as HttpWebRequest;
                getAccessRequest.ContentType = "multipart/form-data";
                getAccessRequest.Timeout = 30000;//30秒连接不成功就中断 
                getAccessRequest.Method = "get";

                HttpWebResponse response = getAccessRequest.GetResponse() as HttpWebResponse;
                using (StreamReader strHttpComback = new StreamReader(response.GetResponseStream(), Encoding.UTF8))
                {
                    string jsonResult = strHttpComback.ReadToEnd();
                    //解析json  
                    JavaScriptSerializer jss = new JavaScriptSerializer();
                    result = jss.Deserialize<PixabayQueryData>(jsonResult);
                }
            }
            catch (WebException ex)
            {

            }
            return result;


        }
        public TagImageList GetImageList(string keywords, int page = 0, int pagesize = 0)
        {
            PixabayQueryData queryResult = Query(keywords);

            List<ImageData> list = new List<ImageData>();
            foreach (var item in queryResult.hits)
            {
                ImageData image = new ImageData();
                image.User = item.user;
                image.From = FROM;
                image.Url_Small = getNewFormatSize(item.webformatURL);
                image.Url_Large = item.webformatURL;
                list.Add(image);
            }

            TagImageList result = new TagImageList();
            result.Total = queryResult.totalHits;
            result.ImageList = list;

            return result;
        }

        private string getNewFormatSize(string url)
        {
            string ext = url.Substring(url.LastIndexOf('.'));
            return url.Replace(url.Substring(url.LastIndexOf('_')), "_340" + ext);
        }
    }
}